package com.eachann.loading.dialog

import android.content.DialogInterface
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction

class LoadingDialog : DialogFragment() {
    private lateinit var animation: AnimationDrawable
    private lateinit var mRootView: View
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NO_FRAME, R.style.ThemeLoadingDialogTransparent)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (!this::animation.isInitialized) {
            mRootView = inflater.inflate(R.layout.dialog_loading_layout, container, false)
            animation =
                mRootView.findViewById<ImageView>(R.id.loading_layout_iamge).drawable as AnimationDrawable
        }
        return mRootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (this::animation.isInitialized) {
            animation.start()
        }
    }

    override fun onDismiss(dialog: DialogInterface) {
        if (this::animation.isInitialized) {
            animation.stop()
        }
        super.onDismiss(dialog)
    }

    companion object {
        private const val TAG = "com.eachann.loading.dialog.LoadingDialog"
        fun show(fragmentManager: FragmentManager) {
            show(fragmentManager, false)
        }

        fun show(fragmentManager: FragmentManager, cancelable: Boolean) {
            val dialogFragment: DialogFragment =
                ((fragmentManager.findFragmentByTag(TAG) ?: LoadingDialog()) as DialogFragment)
            if(dialogFragment.isAdded)return
            dialogFragment.isCancelable = cancelable
            dialogFragment.show(
                fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE),
                TAG
            )
        }

        fun dismiss(fragmentManager: FragmentManager) {
            fragmentManager.findFragmentByTag(TAG)?.run {
                if (this is DialogFragment) {
                    dismissAllowingStateLoss()
                }
            }
        }

    }


}